<template>
  <div class="back_detail">
    <div class="back_content">
      <div class="back_status">
        <div class="back_title">
          <span class="title">售后状态</span>
          <Button label="协商历史" class="history_button" @click="onHistoryClick" />
        </div>

        <template v-if="backDetail.data.backCheck === 'BACK_APPLY'">
          <p class="back_message">待商家审核</p>
          <p class="back_apply">是否同意买家售后申请？</p>
        </template>

        <template v-if="backDetail.data.backCheck === 'DELIVERED'">
          <p class="back_message">买家已退货</p>
          <p class="back_apply">物流单号：{{ backDetail.data.trackingNumber }}</p>
        </template>

        <template v-if="backDetail.data.backCheck === 'RECEIVED'">
          <p class="back_message">已收到买家退回商品</p>

          <div class="refund_proof">
            <span class="refund_title">上传退款凭证</span>
            <!-- <div> -->
            <el-upload class="proof" v-model:file-list="fileList" accept=".jpg,.png,.jpeg" :action="actionUrl" :limit="1" list-type="picture-card" :on-preview="onPictureCardPreview" @before-upload="beforeUpload">
              <div class="img">
                <el-icon class="icon"><Plus /></el-icon>
                <div class="tip" scope.slot="tip">点击上传</div>
              </div>
            </el-upload>
            <span class="upload_tip">只能上传jpg/png文件，且不超过10MB</span>
            <!-- </div> -->

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%" />
            </el-dialog>
          </div>
        </template>

        <p v-if="backDetail.data.backCheck === 'AGREE_BACK'" class="back_message">同意退款，等待买家退货</p>

        <p v-if="backDetail.data.backCheck === 'CONFIRM_RECEIPT'" class="back_message_complete">已完成</p>
      </div>

      <div class="order_info">
        <p class="title">订单信息</p>

        <el-descriptions :column="3" border>
          <el-descriptions-item label="订单编号" label-class-name="my-label" class-name="my-content">{{ backDetail.order.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="订单状态" label-class-name="my-label" span="2" class-name="status">{{ $formater.formaterOrderStatus(backDetail.order.orderStatus) }}</el-descriptions-item>
          <el-descriptions-item label="下单时间" label-class-name="my-label" class-name="my-content">{{ $formater.formatTime(backDetail.order.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间" label-class-name="my-label" class-name="my-content">{{ $formater.formatTime(backDetail.order.paySuccTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付凭证" label-class-name="my-label" class-name="my-content">
            <!-- <el-image v-if="backDetail.order.backPayProof" class="proof_img" ref="previewImg" :src="backDetail.order.backPayProof" :preview-src-list="[backDetail.order.backPayProof]" fit="cover" /> -->

            <div class="proof">
              <img class="proof_img" :src="backDetail.order.payProof" />
              <Link label="查看" class="btn" @click="onShowImgClick(backDetail.order.payProof)" :underline="false" />
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="采购商" label-class-name="my-label" class-name="my-content"
            >{{ backDetail.order.customerName }}
            <Button type="primary" label="查看资质" @click="onShowQualicationClick" />
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="back_order" style="background-color: #fff">
        <div class="back_info">
          <p class="title">售后信息</p>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="售后类型" label-class-name="my-label" class-name="my-content">退货退款</el-descriptions-item>
            <el-descriptions-item label="申请售后时间" label-class-name="my-label" class-name="my-content">{{ backDetail.data.backTime }}</el-descriptions-item>
            <el-descriptions-item label="申请售后原因" label-class-name="my-label" class-name="my-content">{{ backDetail.data.backRemark }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="back_goods">
          <p class="title">售后商品</p>
          <Table :list="backDetail.list" :info="backDetail.data" />
        </div>
      </div>
    </div>

    <div class="audit_button">
      <div class="apply_button" v-if="backDetail.data.backCheck === 'BACK_APPLY'">
        <Button class="button cancel" label="拒绝申请" @click="onRejectClick" />
        <Button class="button confirm" type="primary" label="同意退款" @click="onAgreeClick" />
      </div>

      <Button v-if="backDetail.data.backCheck === 'DELIVERED'" type="primary" label="确认收货" @click="onConfirmClick" />
      <Button v-if="backDetail.data.backCheck === 'RECEIVED'" type="primary" label="提交" @click="onSubmitVoucherClick" />
    </div>

    <el-image-viewer ref="previewViewer" v-if="showImageViewer" @close="closeImgView" :url-list="srcList" />

    <Address v-model:visible="addressVisible" @change="onAddressChange" :supplierId="backDetail.data.supplierId" />
    <History v-model:visible="historyVisible" :list="backDetail.backHistoryList" />
    <Reject v-model:visible="rejectVisible" :orderId="backDetail.data.orderId" @change="onRejectChange" />
    <Qualication v-model:visible="qualicaVisible" :customerId="backDetail.data.customerId" />
  </div>
</template>
<script setup>
import { reactive, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { apiBasePath } from '@/api/config'
import api from '@/api'
import consts from '@/consts'
import formater from '@/formater'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'
import Address from '@/components/address/index.vue'
import Table from '@/components/table/back.vue'
import History from '@/components/history/index.vue'
import Reject from '@/components/reject/index.vue'
import Qualication from '@/components/qualication/index.vue'

const router = useRouter()
const route = useRoute()
const orderId = route.params.id

const backDetail = reactive({
  list: [],
  data: {},
  order: {},
  supplierShippingId: '',
  form: {},
  backHistoryList: [],
  imageUrl: '',
  customerId: ''
})
const loading = ref(false)
const rejectVisible = ref(false)
const addressVisible = ref(false)
const historyVisible = ref(false)
const qualicaVisible = ref(false)
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const fileList = ref([])
const formRef = ref(null)

const srcList = ref([])
const previewViewer = ref()
const showImageViewer = ref(false)

const actionUrl = apiBasePath + '/medinstrument/third/uploadSingleFile'

const uploadVoucher = async () => {
  let payProof = fileList.value.map((e) => e.response.data).join(',')
  let { err } = await api.post(`/medinstrument/third/back/uploadPaymentVoucher?orderId=${orderId}&payProof=${payProof}`)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('退款凭证上传成功')
    loadData()
  }
}

const deliver = async () => {
  let { err } = await api.post(`/medinstrument/third/back/confirmReceipt?orderId=${orderId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('确认收货成功')
    loadData()
  }
}

const audit = async (type, supplierShippingId, remark) => {
  let { err } = await api.post('/medinstrument/third/back/auditBack', {
    operateType: type,
    orderId: backDetail.data.orderId,
    supplierId: backDetail.data.supplierId,
    supplierShippingId: supplierShippingId,
    remark: remark
  })
  if (err) {
    ElMessage.error(err)
  } else {
    if (type === 'PASS') {
      ElMessage.success('审核成功')
    } else {
      ElMessage.success('驳回成功')
    }
    loadData()
  }
}

const loadData = async () => {
  loading.value = true
  let { data, err } = await api.get(`/medinstrument/third/back/getBackDetails?orderId=${orderId}`)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    backDetail.list = data.backOrderGoodsList
    backDetail.backHistoryList = data.backHistoryList?.map((e) => {
      return {
        ...e,
        historyVal: JSON.parse(e.historyVal)
      }
    })
    backDetail.data = data
    backDetail.customerId = data.customerId
  }
}

const orderDetail = async () => {
  loading.value = true
  let { data, err } = await api.get(`/medinstrument/third/order/getOrderdetails?orderId=${orderId}`)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    backDetail.order = data.data
  }
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  const isLt1M = file.size / 1024 / 1024 < 10

  if (!isJPG) {
    ElMessage.error('只能上传jpg/png/jpeg文件!')
  }
  if (!isLt1M) {
    ElMessage.error('上传图片大小不能超过 10MB!')
  }
  return isJPG && isLt1M
}

const FileMax = () => {
  ElMessage.error('超出上传上限')
}

const onRejectClick = () => {
  rejectVisible.value = true
}

const onAgreeClick = () => {
  addressVisible.value = true
}
const onAgreeRefundClick = () => {}

const onShowQualicationClick = () => {
  qualicaVisible.value = true
}
const onAddressChange = (selected) => {
  audit('PASS', selected.supplierShippingId, '')
}

const onRejectChange = (val) => {
  audit('REJECT', 0, val)
}

const onHistoryClick = () => {
  historyVisible.value = true
}

const onConfirmClick = () => {
  deliver()
}

const onPictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}



const onSubmitVoucherClick = () => {
  uploadVoucher()
}

const onShowImgClick = (url) => {
  srcList.value = [url]
  showImageViewer.value = true
}

const closeImgView = () => {
  showImageViewer.value = false
}

onMounted(() => {
  loadData()
  orderDetail()
})
</script>
<style scoped lang="scss">
.back_detail {
  .back_content {
    margin: 10px 15px 10px 10px;

    .title {
      color: var(--color-primary-text);
      height: 16px;
      line-height: 16px;
      font-size: 16px;
      font-weight: 500;
    }

    .back_status {
      padding: 20px 0 20px 20px;
      background-color: #fff;

      .back_title {
        display: flex;
        align-items: center;

        .title {
          display: inline-block;
        }

        .history_button {
          width: 65px;
          height: 24px;
          background-color: #e6f1fc;
          border: 1px solid #a3d0fd;
          margin-left: 10px;
          color: #1989fa;
        }
      }

      .back_message,
      .back_message_complete {
        height: 16px;
        line-height: 16px;
        margin-top: 20px;
        font-size: 15px;
        font-weight: 500;
      }

      .back_message {
        color: #e6a23c;
      }

      .back_message_complete {
        color: #67c23a;
      }

      .back_apply,
      .refund_proof {
        margin-top: 10px;
        padding-top: 10px;
        border-top: 1px solid #e4e7ed;
        color: var(--color-text);
      }

      .back_apply {
        height: 16px;
        line-height: 16px;
      }

      .refund_proof {
        display: flex;

        .refund_title {
          display: inline-block;
          height: 16px;
          line-height: 16px;
          color: var(--color-text);
          margin-right: 25px;
        }

        .upload_tip {
          display: inline-block;
          color: #909399;
          font-size: 12px;
          line-height: 16px;
          margin-top: 8px;
        }
      }
    }

    .order_info {
      padding: 20px 10px 20px 20px;
      margin: 10px 0;
      background-color: #fff;

      .btn {
        margin-left: 20px;
      }

      .orderStatus {
        display: flex;
        align-items: center;

        .payReject {
          position: relative;
        }

        .payReject::after {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          bottom: -6px;
          width: 100%;
          height: 1px;
          background-color: #e6a23c;
        }
      }

      .proof {
        display: flex;
      }
    }

    .back_order {
      padding: 20px 10px 20px 20px;

      .back_goods {
        margin-top: 20px;
        .title {
          margin-bottom: 10px;
        }
      }
    }
  }

  .audit_button {
    .apply_button {
      display: flex;
    }
  }
}
</style>
